﻿using System;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Data.SqlClient;
using System.IO;
using System.Diagnostics;
using Microsoft.Win32;

namespace DATA_SERVER
{
    public partial class MainForm : Form
    {
        Service myService = null;
        LoginForm lgFrm = null;
        System.Threading.Timer DB_timer;
        System.Threading.Timer NetCheck_timer;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Data_Func.mainfrm = this;
            //1 设置自动启动
            SetAutoStart();
            //2 读取配置文件
            if (ConfigForm.ReadConfig())
            {
                Data_Func.ShowText("配置文件读取成功！");
            }
            else
            {
                MessageBox.Show("配置文件读取失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                Application.Exit();
            }

            //3 根据门禁机类型加载对应的类
            switch (Global.MachCode)
            {
                case "ZK":
                    myService = new ZKPUSH_Service();
                    break;
                case "HW":
                    myService = new HANVON_Service();
                    break;
                default:
                    MessageBox.Show("门禁机类型错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    Application.Exit();
                    break;
            }
            //4 初始化 本地/远程 数据库
            InitData();

            //5 如果启动方式为开机启动，则自动启动显示软件
            if (Global.AutoStart)
            {
                StartService(); //启动服务

                Thread.Sleep(10000);
                if (File.Exists(Application.StartupPath + @"\门禁显示软件.exe"))
                {
                    Process.Start(Application.StartupPath + @"\门禁显示软件.exe");
                }
            }
            else
            {
                //手动启动需要先登录，否则退出
                if (!UserLogin())
                {
                    Application.Exit();
                }
                StartService();  //启动服务
                //this.startToolStripMenuItem.PerformClick();         // 触发启动菜单
            }
        }

        private void SetAutoStart()
        {
            RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            RKey.SetValue("DATA_SERVER", "\"" + Application.ExecutablePath + "\" -start");
        }

        private bool UserLogin()
        {
            if (!DB_SQLServer.b_Init)
            {
                return true;
            }
            while (true)
            {
                if (lgFrm == null)
                {
                    lgFrm = new LoginForm();
                }
                if (lgFrm.ShowDialog(this) == DialogResult.OK)
                {
                    SqlDataReader reader = DB_SQLServer.ExecuteReader(string.Format("SELECT * FROM [SYS_USER] INNER JOIN [SYS_USER_ROLE] ON [SYS_USER].[USERID] = [SYS_USER_ROLE].[USERID] WHERE [SYS_USER].[LOGINNAME] = '{0}' AND [SYS_USER].[LOGINPWD] = '{1}' AND [SYS_USER_ROLE].[ROLEID] = '3000'", LoginForm.user, Data_Func.MD5(LoginForm.password)));
                    if (reader.Read())
                    {
                        reader.Close();
                        lgFrm.Dispose();
                        lgFrm = null;
                        return true;
                    }
                    reader.Close();
                }
                else
                {
                    lgFrm.Dispose();
                    lgFrm = null;
                    return false;
                }
                lgFrm.Dispose();
                lgFrm = null;
            }
        }

        private void InitData()
        {
            if (DB_SQLite.Init())
            {
                Data_Func.ShowText("本地数据库初始化成功！");
            }
            else
            {
                MessageBox.Show("本地数据库初始化失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                Application.Exit();
            }

            if (DB_SQLServer.Init())
            {
                Data_Func.ShowText("远程数据库初始化成功！");
            }
            else
            {
                Data_Func.ShowText("远程数据库初始化失败！");
            }
        }

        void StartService()
        {
            if (DB_SQLServer.b_Init)
            {
                DB_SQLite.UpdateBeacon();
            }

            if (myService != null)
            {
                myService.StartService();
            }

            Display_Func.StartService();
            Data_Thread.StartThread();
            DB_timer = new System.Threading.Timer(new TimerCallback(DB_SQLite.UpdateDB), myService, Global.DBInterval * 1000, Global.DBInterval * 1000);
            NetCheck_timer = new System.Threading.Timer(new TimerCallback(Service.GetStatus), myService, Global.NetInterval * 1000, Global.NetInterval * 1000);

            startToolStripMenuItem.Enabled = false;//启动工具条菜单项
            stopToolStripMenuItem.Enabled = true;//停止工具条菜单项
            SyntoolStripMenuItem.Enabled = true;//系统工具条菜单项
            DeltoolStripMenuItem.Enabled = true;//删除系统工具条菜单项
            configtoolStripMenuItem.Enabled = false;//配置系统工具条菜单项
        }

        void StopService()
        {
            if (myService != null)
            {
                myService.StopService();
            }

            Display_Func.StopService();
            Data_Thread.EndThread();
            if (DB_timer != null)
            {
                DB_timer.Dispose();
            }
            if (NetCheck_timer != null)
            {
                NetCheck_timer.Dispose();
            }

            startToolStripMenuItem.Enabled = true;
            stopToolStripMenuItem.Enabled = false;
            SyntoolStripMenuItem.Enabled = false;
            DeltoolStripMenuItem.Enabled = false;
            configtoolStripMenuItem.Enabled = true;
        }

        public void AddText(string text)
        {
            if (tb_Log.TextLength > 10000)
            {
                tb_Log.Clear();
            }
            tb_Log.AppendText(text + "\r\n");
        }


        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                StartService();

                if (ConfigForm.Resync)
                {
                    if (MessageBox.Show("修改的某些设置需要重新同步用户才能生效，是否现在开始？", "同步用户信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        Thread Syn_Thread = new Thread(new ParameterizedThreadStart(DB_SQLServer.Synchronize));
                        Syn_Thread.IsBackground = true;
                        Syn_Thread.Start(myService);
                        ConfigForm.Resync = false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }

        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StopService();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!UserLogin())
            {
                return;
            }
            if (MessageBox.Show("是否确定要退出？", "退出", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tb_Log.Clear();
        }

        private void SyntoolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确定要同步用户信息？", "同步用户信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.No)
            {
                return;
            }
            Thread Syn_Thread = new Thread(new ParameterizedThreadStart(DB_SQLServer.Synchronize));
            Syn_Thread.IsBackground = true;
            Syn_Thread.Start(myService);
        }

        private void DeltoolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确定要清除用户信息？", "清除用户信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.No)
            {
                return;
            }
            Thread Syn_Thread = new Thread(new ParameterizedThreadStart(DB_SQLServer.ClearUser));
            Syn_Thread.IsBackground = true;
            Syn_Thread.Start(myService);
        }

        private void configtoolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConfigForm CfgFrm = new ConfigForm();
            CfgFrm.ShowDialog(this);
            if (ConfigForm.ReInit)
            {
                InitData();
                ConfigForm.ReInit = false;
            }
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)    //最小化到系统托盘
            {
                notifyIcon.Visible = true;    //显示托盘图标
                this.Hide();    //隐藏窗口
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;    //取消"关闭窗口"事件
                this.WindowState = FormWindowState.Minimized;    //使关闭时窗口向右下角缩小的效果
                notifyIcon.Visible = true;
                this.Hide();
                return;
            }
            else
            {
                StopService();
            }
        }

        public void ShowWnd()
        {
            if (!UserLogin())
            {
                return;
            }
            notifyIcon.Visible = false;
            this.Show();
            WindowState = FormWindowState.Normal;
            this.TopMost = true;
            this.TopMost = false;
            this.Focus();
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowWnd();
        }

        private void ShowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowWnd();
        }

        private void QuitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!UserLogin())
            {
                return;
            }
            if (MessageBox.Show("是否确定要退出？", "退出", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            if (Global.AutoStart)
            {
                this.WindowState = FormWindowState.Minimized;    //使关闭时窗口向右下角缩小的效果
                notifyIcon.Visible = true;
                this.Hide();
            }
        }
    }
}